import requests
import json
from tqdm import tqdm
from log import logger
from util import get_random_useragent_phone

version = "2.2"

def GetVersion():
    url = "http://:5000/getVersion"
    headers = {
        "User-Agent":get_random_useragent_phone(),
        'Content-Type': 'application/json'
    }
    data = {"version":version}
    data = json.dumps(data)

    try:
        resp = requests.post(url=url, headers=headers, data=data)
        resp_json = json.loads(resp.text)
        if resp_json["code"] == 1:
            newVersion = resp_json["version"]
            if version != newVersion:
                logger.info("检测到新版本,请等待更新")
                downloadUrl = "http:///NewBee_V{}.exe".format(newVersion)
                Download(downloadUrl, "NewBee_V{}.exe".format(newVersion))
                logger.info("更新完成,请重新打开新版软件")
                return True
            else:
                logger.info("当前版本为最新")
                return True
        else:
            logger.error("版本更新检测失败")
            return False
    except Exception as e:
        logger.error("版本更新检测失败: %s", e)
        return False
    
def Download(url: str, fname: str):
    # 用流stream的方式获取url的数据
    resp = requests.get(url, stream=True)
    # 拿到文件的长度，并把total初始化为0
    total = int(resp.headers.get('content-length', 0))
    # 打开当前目录的fname文件(名字你来传入)
    # 初始化tqdm，传入总数，文件名等数据，接着就是写入，更新等操作了
    with open(fname, 'wb') as file, tqdm(
        desc=fname,
        total=total,
        unit='iB',
        unit_scale=True,
        unit_divisor=1024,
    ) as bar:
        for data in resp.iter_content(chunk_size=1024):
            size = file.write(data)
            bar.update(size)
